package com.teacher.service.impl;

import com.teacher.entity.LearningPerformance;
import com.teacher.repository.LearningPerformanceRepository;
import com.teacher.service.LearningPerformanceService;
import com.teacher.untils.ApplictionElum;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.Predicate;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
@Transactional
public class LearningPerformanceServiceImp implements LearningPerformanceService {
    @Autowired
    LearningPerformanceRepository learningPerformanceRepository;

    /**
     * 批量导入
     * @param file,academicYear
     * @return
     */
    @Override
    public String uploadCommentsOfExcel(MultipartFile file,String academicYear) {
        try {
            // 根据路径获取这个操作excel的实例
            XSSFWorkbook wb = new XSSFWorkbook(file.getInputStream());
            // 根据页面index 获取sheet页
            XSSFSheet sheet = wb.getSheetAt(0);
            // 实体类集合
            List<LearningPerformance> importData = new ArrayList<>();
            XSSFRow row = null;
            // 循环sheet页中数据从第二行开始，第一行是标题
            for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
                // 获取每一行数据
                row = sheet.getRow(i);
                LearningPerformance data = new LearningPerformance();

                XSSFCell cell = row.getCell(0);
                cell.setCellType(CellType.STRING);
                data.setStudentNumber(cell.getStringCellValue());
                cell = row.getCell(1);
                cell.setCellType(CellType.STRING);
                data.setStudentId(cell.getStringCellValue());
                cell = row.getCell(2);
                cell.setCellType(CellType.STRING);
                data.setSchoolId(cell.getStringCellValue());
                cell = row.getCell(3);
                cell.setCellType(CellType.STRING);
                data.setGradeId(cell.getStringCellValue());
                cell = row.getCell(4);
                cell.setCellType(CellType.STRING);
                data.setClassId(cell.getStringCellValue());
                cell = row.getCell(5);
                cell.setCellType(CellType.STRING);
                data.setLateNumber(cell.getStringCellValue());
                cell = row.getCell(6);
                cell.setCellType(CellType.STRING);
                data.setSickleaveNumber(cell.getStringCellValue());
                cell = row.getCell(7);
                cell.setCellType(CellType.STRING);
                data.setCompassionateLeaveNumber(cell.getStringCellValue());
                cell = row.getCell(8);
                cell.setCellType(CellType.STRING);
                data.setTruancyNumber(cell.getStringCellValue());
                cell = row.getCell(9);
                cell.setCellType(CellType.STRING);
                data.setPerformanceMaterials(cell.getStringCellValue());
                data.setCreateDate(new Date());
                data.setUpdateDate(new Date());
                data.setAcademicYear(academicYear);
                data.setDelFlag("0");
                data.setCreateBy("0");
                data.setUpdateBy("0");
                importData.add(data);
            }
            //导入数据库
            for (LearningPerformance data : importData) {
                learningPerformanceRepository.save(data);
            }
            }catch(Exception e){
                e.printStackTrace();
                return ApplictionElum.REST_IMPORT_FAIL + e.getMessage();
            }
            return ApplictionElum.REST_IMPORT_OK;
        }

    /**
     * 增加
     * @param learningPerformance
     * @return
     */
    @Override
    public LearningPerformance addLearningPerformance(LearningPerformance learningPerformance) {
        return learningPerformanceRepository.save(learningPerformance);
    }

    /**
     * 查看详情
     * @param id
     */
    @Override
    public LearningPerformance getDetailsById(String id) {

        return learningPerformanceRepository.findById(Integer.valueOf(id)).get();
    }

    /**
     * 删除
     * @param id
     */
    @Override
    public void deleteLearningPerformance(String id) {
        LearningPerformance learningPerformance = null;
        try {
            learningPerformance = learningPerformanceRepository.findById(Integer.valueOf(id)).get();
            learningPerformanceRepository.delete(learningPerformance);
        } catch (RuntimeException e) {
            e.printStackTrace();
        }
    }

    /**
     * 批量删除
     * @param idList
     */
    @Override
    public void deleteLearningPerformanceList(String idList) {
        String[] split = idList.split(",");
        List<Integer> list = new ArrayList<>();
        for (String s : split) {
            list.add(Integer.parseInt(s));
        }
        learningPerformanceRepository.deleteLearningPerformancesByIdIn(list);
    }

    /**
     * 根据条件分页查询
     * @param learningPerformance,page,size
     */
    @Override
    public Page<LearningPerformance> specificPageQueryLearningPerformanceList(LearningPerformance learningPerformance, int page, int size) {
        Specification querySpecification = (Specification<LearningPerformance>) (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<Predicate>();
            if(learningPerformance != null)
            {
                // 学年学期
                String academicYear = learningPerformance.getAcademicYear();
                String gradeId = learningPerformance.getGradeId();
                String classId = learningPerformance.getClassId();
                if (!StringUtils.isEmpty(academicYear)) {
                    predicates.add(cb.equal(root.get("academicYear").as(String.class), academicYear));
                }
                if (!StringUtils.isEmpty(gradeId)) {
                    predicates.add(cb.equal(root.get("gradeId").as(String.class), gradeId));
                }
                if (!StringUtils.isEmpty(classId)) {
                    predicates.add(cb.equal(root.get("classId").as(String.class), classId));
                }
            }

            return cb.and(predicates.toArray(new Predicate[predicates.size()]));
        };
        return learningPerformanceRepository.findAll(querySpecification,PageRequest.of(page-1,size));
    }
}
